<template>
  <div class="new-seckill-add-or-update">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          !dataForm.seckillId
            ? $t('seckill.newSeckill')
            : $t('seckill.viewSeckill')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      class="form-box"
      label-width="78px"
      @submit.prevent
      @keyup.enter="dataFormSubmit()"
    >
      <el-form-item
        :label="$t('group.actName')"
        prop="seckillName"
        class="seckill-name-input"
      >
        <el-input
          v-model.trim="dataForm.seckillName"
          style="width: 508px"
          maxlength="36"
          show-word-limit
          :disabled="!!dataForm.seckillId"
        />
      </el-form-item>
      <el-form-item
        :label="$t('marketing.activTime')"
        prop="startTime"
      >
        <el-date-picker
          v-model="dataForm.startTime"
          value-format="YYYY-MM-DD"
          type="date"
          :placeholder="$t('time.start')"
          :disabled="!!dataForm.seckillId"
          style="width:136px"
        />
        <el-time-select
          v-model="startTimeValue"
          start="00:00"
          step="00:30"
          end="23:30"
          :class="[startTimeValue ? 'select-time': '']"
          style="width:106px"
          :disabled="!!dataForm.seckillId"
          :placeholder="$t('time.startTime')"
        />
        <span style="margin:0 5px;width:14px;display: inline-block;">{{ $t('time.tip') }}</span>
        <el-date-picker
          v-model="dataForm.endTime"
          value-format="YYYY-MM-DD"
          type="date"
          :placeholder="$t('time.end')"
          :disabled="!!dataForm.seckillId"
          style="width:136px"
        />
        <el-time-select
          v-model="endTimeValue"
          start="00:00"
          step="00:30"
          end="23:30"
          :class="[endTimeValue ? 'select-time': '']"
          style="width:106px"
          :disabled="!!dataForm.seckillId"
          :placeholder="$t('time.endTime')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('seckill.purcPerPerson')"
        prop="maxNum"
      >
        <el-checkbox
          v-model="hasMaxNum"
          :disabled="!!dataForm.seckillId"
          @click="handlerChangeMaxNum"
        >
          {{ $t("seckill.openPurchaseLimit") }}
        </el-checkbox>
        <span v-show="hasMaxNum">
          {{ $t("seckill.canBePurcPer") }}
          <el-input-number
            v-model="dataForm.maxNum"
            controls-position="right"
            :min="1"
            :max="1000"
            style="width: 100px"
            :disabled="!!dataForm.seckillId"
            :precision="0"
          />{{ $t("marketing.item") }}
        </span>
      </el-form-item>
      <el-form-item
        :label="$t('seckill.cancelTheOrder')"
        prop="maxCancelTime"
      >
        {{ $t("order.buyer") }}&nbsp;
        <el-input-number
          v-model="dataForm.maxCancelTime"
          :min="2"
          :max="15"
          controls-position="right"
          style="width: 100px"
          :disabled="!!dataForm.seckillId"
          :precision="0"
        />&nbsp;&nbsp;{{ $t("seckill.unpaidnutes")
        }}
      </el-form-item>
      <el-form-item
        :label="$t('home.product')"
        :required="true"
      >
        <div
          v-if="!dataForm.seckillId && prod === null"
          style="float: left"
          class="default-btn"
          @click="prodsSelectHandle()"
        >
          {{ $t("product.select") }}
        </div>
        <el-alert
          :title="$t('seckill.warning')"
          type="warning"
          :closable="false"
          style="width: 295px; float: left; height: 32px; margin-left: 10px"
        />
      </el-form-item>
      <el-form-item
        v-if="prod != null"
        label=""
      >
        <el-card
          :body-style="{ padding: '0px' }"
          style="height: 160px; width: 120px"
        >
          <prod-pic
            height="104px"
            width="100%"
            :pic="prod.pic"
          />
          <div class="card-prod-bottom">
            <span class="card-prod-name">{{ prod.prodName }}</span>
            <el-button
              v-if="prod.status !== -1 && !dataForm.seckillId"
              type="text"
              class="card-prod-name-button"
              :disabled="!!dataForm.seckillId"
              @click="deleteProd"
            >
              {{ $t("text.delBtn") }}
            </el-button>
            <el-button
              v-if="prod.status === -1"
              type="text"
              class="card-prod-name-button"
              disabled
            >
              {{ $t("seckill.productHasBeenDeleted") }}
            </el-button>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item v-if="skuList.length">
        <!--      批量设置-->
        <div>
          <el-form
            v-if="isEdit"
            :inline="true"
            class="demo-form-inline"
            @submit.prevent
          >
            <el-form-item :label="$t('product.eventPrice')">
              <el-input-number
                v-model="dataForm.price"
                controls-position="right"
                :precision="2"
                :max="1000000000"
                :min="0"
              />
            </el-form-item>
            <el-form-item :label="$t('marketing.activeInventory')">
              <el-input-number
                v-model="dataForm.stocks"
                controls-position="right"
                :disabled="isCompose == 1"
                :precision="0"
                :max="9999999"
                :min="0"
              />
            </el-form-item>
            <el-form-item label="">
              <div
                class="default-btn primary-btn"
                @click="batchSet"
              >
                {{ $t("crud.filter.submitBtn") }}
              </div>
              <div
                class="default-btn"
                @click="switchSet"
              >
                {{ $t("crud.filter.cancelBtn") }}
              </div>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-if="skuList.length"
          :data="skuList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 1000px; margin-top: 20px"
        >
          <el-table-column
            prop="prodName"
            :label="$t('product.prodName')"
            width="350"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.prodName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            :label="$t('product.eventPrice')"
            :width="lang === 'en' ? '251' : '201'"
          >
            <template #default="scope">
              <el-input-number
                v-model="scope.row.seckillPrice"
                :precision="2"
                :step="0.01"
                :min="0.01"
                :max="!!(!scope.row.status || dataForm.seckillId) ? 100000000 : scope.row.price"
                :disabled="!!(!scope.row.status || dataForm.seckillId)"
              />
              <div>{{ $t("seckill.price") }}{{ scope.row.price }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="stocks"
            :label="$t('marketing.activeInventory')"
            width="201"
          >
            <template #default="scope">
              <el-input-number
                v-model="scope.row.seckillStocks"
                type="number"
                :step-strictly="true"
                :min="0"
                :max="9999999"
                :disabled="!!(!scope.row.status || dataForm.seckillId)"
              />
              <div>{{ $t("seckill.exisocks") }}{{ scope.row.stocks }}</div>
            </template>
          </el-table-column>
          <el-table-column :label="!dataForm.seckillId ? $t('text.menu') : $t('product.status')">
            <template #default="scope">
              <div v-if="!dataForm.seckillId">
                <el-button
                  v-if="scope.row.status"
                  type="text"
                  :disabled="!!dataForm.seckillId"
                  @click="changeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("publics.disable") }}
                </el-button>
                <el-button
                  v-else
                  type="text"
                  :disabled="!!(scope.row.rawStatus === 0 || dataForm.seckillId)"
                  @click="changeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("shop.ena") }}
                </el-button>
              </div>
              <div v-else>
                <el-button
                  v-if="!scope.row.seckillPrice"
                  type="text"
                  :disabled="!!dataForm.seckillId"
                  @click="changeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("publics.disable") }}
                </el-button>
                <el-button
                  v-else
                  type="text"
                  :disabled="!!dataForm.seckillId"
                  @click="changeSkuStatus(`${scope.$index}`)"
                >
                  {{ $t("shop.ena") }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="back()"
        >
          {{
            $t("crud.filter.cancelBtn")
          }}
        </div>
        <div
          type="primary"
          class="default-btn primary-btn"
          :class="[!!dataForm.seckillId ? 'disabled-btn' : '', 'default-btn primary-btn']"
          @click="dataFormSubmit(!!dataForm.seckillId)"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </el-form-item>
    </el-form>
    <!-- 商品选择弹窗 -->
    <!-- 如果要更改dataUrl，在商品选择组件选择商品后的判断处也要更改一下 -->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      :prod-type="0"
      @refresh-select-prods="selectSeckillProd"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { getDateTimeRange, getParseTime } from '@/utils/datetime'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])
const validatorDateRange = (rule, value, callback) => {
  if (!Data.dataForm.startTime || !Data.dataForm.endTime || !Data.startTimeValue || !Data.endTimeValue) {
    callback(new Error($t('seckill.pleaheyTime')))
  }
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  const endTime = Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00'
  if (!Data.dataForm.seckillId && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  } else if (Date.parse(endTime) <= Date.parse(startTime)) {
    callback(new Error($t('groups.endTimeIsTooSmall')))
  } else {
    callback()
  }
}

const Data = reactive({
  prodsSelectVisible: false,
  hasMaxNum: false,
  isEdit: false,
  lang: localStorage.getItem('bbcLang'),
  dataForm: {
    dateRange: [],
    seckillId: null,
    seckillName: null,
    startTime: null,
    endTime: null,
    seckillTag: null,
    maxNum: 1,
    hasMaxNum: false,
    maxCancelTime: 2,
    price: null,
    stocks: null
  },
  prod: null,
  skuList: [],
  isError: false,
  value: '',
  dataRule: {
    seckillName: [
      { required: true, message: $t('seckill.evenBeEmpty'), trigger: 'blur' }
    ],
    maxCancelTime: [
      { required: true, message: $t('seckill.theOrionEmpty'), trigger: 'blur' }
    ],
    startTime: [
      { required: true, validator: validatorDateRange, trigger: 'blur' }
    ]
  },
  startTimeValue: '',
  endTimeValue: ''
})

const { prodsSelectVisible, hasMaxNum, isEdit, lang, dataForm, prod, skuList, dataRule, startTimeValue, endTimeValue } = toRefs(Data)

const route = useRoute()
const commonStore = useCommonStore()
onMounted(() => {
  const seckillId = route.query.seckillId
  init(seckillId)
  const title = !seckillId ? $t('seckill.newSeckill') : $t('seckill.viewSeckill')
  commonStore.replaceSelectMenu(title)
})

const dataFormRef = ref()
const init = (seckillId) => {
  dataFormRef.value.resetFields()
  Data.prod = null
  Data.skuList = []
  Data.dataForm.seckillId = seckillId || 0
  Data.hasMaxNum = false
  const datetimeRange = getDateTimeRange()
  Data.dataForm.startTime = datetimeRange.startTime
  Data.dataForm.endTime = datetimeRange.endTime
  Data.startTimeValue = datetimeRange.currentTime
  Data.endTimeValue = datetimeRange.currentTime
  if (Data.dataForm.seckillId) {
    http({
      url: http.adornUrl('/seckill/seckill/info/' + Data.dataForm.seckillId),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      Data.dataForm = data.seckill
      Data.startTimeValue = Data.dataForm.startTime ? Data.dataForm.startTime.substring(11, Data.dataForm.startTime.length - 3) : ''
      Data.endTimeValue = Data.dataForm.endTime ? Data.dataForm.endTime.substring(11, Data.dataForm.endTime.length - 3) : ''
      Data.dataForm.startTime = getParseTime(Data.dataForm.startTime, '{y}-{m}-{d}')
      Data.dataForm.endTime = getParseTime(Data.dataForm.endTime, '{y}-{m}-{d}')
      Data.hasMaxNum = data.seckill.maxNum > 0
      Data.prod = data.prod
      getSkuList(data.prod.prodId, data.seckillSkus)
    })
  }
}

const switchSet = () => {
  Data.isEdit = !Data.isEdit
  if (!Data.isEdit) {
    Data.dataForm.price = 0
    Data.dataForm.stocks = 0
  }
}

const batchSet = () => {
  Data.skuList.forEach(sku => {
    if (Data.dataForm.price) {
      sku.seckillPrice = Data.dataForm.price
    }
    if (Data.dataForm.stocks) {
      sku.seckillStocks = Data.dataForm.stocks
    }
  })
  Data.isEdit = false
}

const getSkuList = (prodId, seckillSkus) => {
  http({
    url: http.adornUrl('/sku/getAllSkuList'),
    method: 'get',
    params: http.adornParams({
      prodId
    })
  }).then(({ data }) => {
    if (seckillSkus) {
      data.forEach(sku => {
        seckillSkus.forEach(seckillSku => {
          if (sku.skuId === seckillSku.skuId) {
            sku.seckillStocks = seckillSku.seckillStocks
            sku.seckillPrice = seckillSku.seckillPrice
          }
        })
      })
    }
    data.forEach(sku => {
      sku.rawStatus = sku.status
    })
    Data.skuList = data
  })
}

/**
* 判断sku中的商品价格与库存是否有填写
*/
const checkSku = () => {
  Data.isError = false
  let disableNum = 0
  Data.skuList.forEach(element => {
    if (!element.seckillPrice && element.status === 1) {
      Data.isError = true
      Data.value = $t('seckill.commoBeEmpty')
      return true
    }
    if (!element.seckillStocks && element.seckillStocks !== 0 && element.status === 1) {
      Data.isError = true
      Data.value = $t('seckill.commodiBeEmpty')
      return true
    }
    if (element.seckillStocks === 0) {
      Data.isError = true
      Data.value = $t('seckill.skuStockNotZero')
      return true
    }
    if (element.status === 0) {
      disableNum += 1
    }
  })
  if (disableNum === Data.skuList.length) {
    Data.isError = true
    Data.value = $t('seckill.enableMustOne')
    return true
  }
}

// 表单提交
const dataFormSubmit = Debounce((status) => {
  if (status) {
    return
  }
  // 秒杀不能更新
  if (Data.dataForm.seckillId) {
    back()
    return
  }
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (!Data.prod) {
        ElMessage({
          message: $t('seckill.pleaSenProc'),
          type: 'error'
        })
        return
      }
      if (!Data.hasMaxNum) {
        Data.dataForm.maxNum = -1
      }
      // 判断sku中的商品价格与库存是否有填写
      checkSku()
      if (Data.isError) {
        ElMessage.error(Data.value)
        return
      }
      const startTime = Data.dataForm.startTime
      const endTime = Data.dataForm.endTime
      Data.dataForm.startTime = Data.dataForm.startTime && Data.startTimeValue ? Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00' : ''
      Data.dataForm.endTime = Data.dataForm.endTime && Data.endTimeValue ? Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00' : ''
      Data.dataForm.prodId = Data.prod.prodId
      Data.dataForm.seckillSkus = Data.skuList.filter(sku => sku.status)

      const paramData = Object.assign({}, Data.dataForm)
      paramData.hasMaxNum = Data.hasMaxNum ? 1 : 0
      http({
        url: http.adornUrl('/seckill/seckill'),
        method: 'post',
        data: http.adornData(paramData)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            back()
            emit('refreshDataList')
          }
        })
      })
      Data.dataForm.startTime = startTime
      Data.dataForm.endTime = endTime
    }
  })
})

const prodsSelectRef = ref()
// 显示添加指定商品弹框
const prodsSelectHandle = () => {
  Data.prodsSelectVisible = true
  nextTick(() => {
    prodsSelectRef.value.init(Data.dataForm.discountProds)
  })
}

const handlerChangeMaxNum = (val) => {
  if (val) {
    Data.dataForm.maxNum = 1
  } else {
    Data.dataForm.maxNum = -1
  }
}

// 添加指定商品
const selectSeckillProd = (prods) => {
  if (prods.prodId) {
    if (prods.pic) {
      prods.pic = checkFileUrl(prods.pic)
    }
    Data.prod = prods
    getSkuList(prods.prodId)
  } else {
    Data.skuList = []
    Data.prod = null
  }
}

const deleteProd = () => {
  Data.prod = null
  Data.skuList = []
}

const changeSkuStatus = (tagIndex) => {
  Data.skuList[tagIndex].status = Data.skuList[tagIndex].status ? 0 : 1
}

const router = useRouter()
const back = () => {
  router.push('/marketing/seckill/index')
}
</script>

<style lang="scss" scoped>
.new-seckill-add-or-update {

  div ::v-deep(.is-success .el-input-number__decrease),
  div ::v-deep(.is-success .el-input-number__increase),
  div ::v-deep(.is-error .el-input-number__decrease),
  div ::v-deep(.is-error .el-input-number__increase) {
    right: 1px !important;
  }

  div ::v-deep(.el-date-editor .el-range-separator) {
    width: 8%;
    line-height: 32px;
  }

  .form-box {
    margin-left: 40px;
  }

  .seckill-name-input ::v-deep(.el-input__inner) {
    padding-right: 45px !important;
  }

  :deep(.el-select .el-input__suffix-inner){
      display: none;
    }
  .select-time:hover :deep(.el-input__suffix-inner){
    display: inline-flex;
  }
}
</style>
